package com.ywm.eduOrder.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import com.ywm.eduOrder.entity.TOrder;
import com.ywm.eduOrder.entity.TPayLog;
import com.ywm.eduOrder.mapper.TPayLogMapper;
import com.ywm.eduOrder.service.TOrderService;
import com.ywm.eduOrder.service.TPayLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ywm.eduOrder.utils.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-06-06
 */
@Service
public class TPayLogServiceImpl extends ServiceImpl<TPayLogMapper, TPayLog> implements TPayLogService {
    @Autowired
    private TOrderService orderService;
    @Override
    public Map<String, String> createNative(String orderNo) {
        Map map=null;
        try {
            //1.根据订单号查询订单信息
            QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no",orderNo);
            TOrder order = orderService.getOne(wrapper);
            //2.使用map设置生成二维码需要的参数
            Map<String, String> m=new HashMap<>();
            m.put("appid","wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("nonce_str", WXPayUtil.generateNonceStr());//随机生成的二维码
            m.put("body", order.getCourseTitle());//课程标题
            m.put("out_trade_no", orderNo);//订单号
            m.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");//转换价格的格式
            m.put("spbill_create_ip", "127.0.0.1");//微信支付地址
            m.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");//支付后回调的地址
            m.put("trade_type", "NATIVE");//支付的类型
            //3.发送HTTPClient请求，传递参数xml格式，微信支付提供的固定地址
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置xml的参数
            client.setXmlParam(WXPayUtil.generateSignedXml(m,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);//支持https
            client.post();//发送
            //得到发送请求返回结果
            String xml = client.getContent();//返回的是xml格式
            Map<String,String> resultMap = WXPayUtil.xmlToMap(xml);//将xml转换为map
            System.out.println("+++++++++++++++++++++++++++"+resultMap+"++++++++++++++++++");
            //4、封装返回结果集
            map= new HashMap<>();
            map.put("out_trade_no", orderNo);
            map.put("course_id", order.getCourseId());
            map.put("total_fee", order.getTotalFee());
            map.put("result_code", resultMap.get("result_code"));//返回二维码操作的状态码
            map.put("code_url", resultMap.get("code_url"));//二维码地址

        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
    //查询订单的支付状态
    @Override
    public Map queryPayStatus(String orderNo) {
        try {
            //1、封装参数
            Map m = new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //2、设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            //6、转成Map
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //7、返回
            System.out.println(888888);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("+++++++++***********+++++++++");
        return null;
    }
    //添加支付记录和更新订单状态
    @Override
    public void updateOrdersStatus(Map map) {
        //获取订单id
        String orderNo = (String) map.get("out_trade_no");
        //根据订单id查询订单信息
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        TOrder order = orderService.getOne(wrapper);

        if(order.getStatus().intValue() == 1) return;
        order.setStatus(1);
        orderService.updateById(order);

        //记录支付日志
        TPayLog payLog=new TPayLog();
        payLog.setOrderNo(order.getOrderNo());//支付订单号
        payLog.setPayTime(new Date());
        payLog.setPayType(1);//支付类型
        payLog.setTotalFee(order.getTotalFee());//总金额(分)
        payLog.setTradeState((String) map.get("trade_state"));//支付状态
        payLog.setTransactionId((String) map.get("transaction_id"));
        payLog.setAttr(JSONObject.toJSONString(map));
        baseMapper.insert(payLog);//插入到支付日志表
    }
}
